#include "AudioObject.h"
#include "world.h"

AudioObject::AudioObject(QDeclarativeItem *parent)
    : QDeclarativeItem(parent)
{
    setFlag(QGraphicsItem::ItemHasNoContents, true);
}

AudioObject::~AudioObject()
{
    if (m_Buffer != 0)
    {
        delete m_Buffer;
        m_Buffer = 0;
    }
}

void AudioObject::setSource(QString source)
{
    m_Source = source;
    emit sourceChanged(source);

    if (World *world = dynamic_cast<World *>(this->parent()))
    {
        m_Buffer = world->addAudio(source);
    }
}

void AudioObject::play()
{
    //workaround
    if (m_Buffer == 0)
    {
        if (World *world = dynamic_cast<World *>(this->parent()))
        {
            m_Buffer = world->addAudio(m_Source);
        }
    }

    if (m_Buffer != 0)
    {
        if (World *world = dynamic_cast<World *>(this->parent()))
        {
            m_Effect = m_Buffer->playWithMixer(world->getMixer());
        }
    }
}

void AudioObject::stop()
{
    if (m_Effect != 0)
    {
        m_Effect->stop();
    }
}

void AudioObject::playWithLoop()
{
    //workaround
    if (m_Buffer == 0)
    {
        if (World *world = dynamic_cast<World *>(this->parent()))
        {
            m_Buffer = world->addAudio(m_Source);
        }
    }

    if (m_Buffer != 0)
    {
        if (World *world = dynamic_cast<World *>(this->parent()))
        {
            m_Effect = m_Buffer->playWithMixer(world->getMixer());
            m_Effect->setLoopCount(-1);
        }
    }
}
